package com.g02.zy;

public class HomeWork {
    public static void main(String[] args) {
        // 初始化出十位同学的链表
        ListNode head = new ListNode(1);
        ListNode cur = head;
        for (int i = 2; i < 11; i++) {
            cur.next = new ListNode(i);
            cur = cur.next;
        }

        // 打印
        System.out.println("初始化的序列:");
        show(head);

        // 将奇偶节点分开
        ListNode odd = head;
        ListNode even = head.next;
        boolean flag = false;  // 假 则加入 odd
        ListNode p1 = odd;
        ListNode p2 = even;
        cur = even.next;
        while (cur != null) {
            if (flag) {
                p2.next = cur;
                p2 = p2.next;
                flag = false;
            } else {
                p1.next = cur;
                p1 = p1.next;
                flag = true;
            }
            cur = cur.next;
        }
        p1.next = null;
        p2.next = null;

        // 打印
        System.out.println("奇数节点:");
        show(odd);
        System.out.println("偶数节点:");
        show(even);

        // 偶节点反转
        even = reverse(even);
        System.out.println("反转后的偶数节点:");
        show(even);

        // 最后的拼接
        ListNode res = null;
        cur = res;
        p1 = odd;
        p2 = even;
        while (p1 != null || p2 != null) {
            if (p1 != null) {
                if (cur == null) {
                    res = p1;
                } else {
                    cur.next = p1;
                }
                cur = p1;
                p1 = p1.next;
            }
            if (p2 != null) {
                cur.next = p2;
                cur = p2;
                p2 = p2.next;
            }
        }

        // 输出最后的结果
        System.out.println("编排完成后的学习小组:");
        show(res);
    }

    static ListNode reverse(ListNode head) {
        // 封装一个无头节点的反转
        ListNode prev = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }

    static void show(ListNode head) {
        // 封装一个打印链表的函数
        ListNode cur = head;
        while (cur != null) {
            System.out.printf("%d->", cur.val);
            cur = cur.next;
        }
        System.out.print("\n");  // 最后补充一个换行
    }
}

class ListNode {
    // 力扣的定义来定义一个链表
    public int val;
    public ListNode next;
    public ListNode() {}
    public ListNode(int val) { this.val = val; }
    public ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
